package processFunction;

import beans.SenSorReading;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * 检测一段时间内的温度连续上升，输出报警
 */
public class Process_Appaction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> inputStream = env.socketTextStream("hadoop", 9999);

        SingleOutputStreamOperator<SenSorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SenSorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        /**
         * 测试keyedProcessed
         * 先分组然后自定义处理
         */
        dataStream.keyBy("id")
                .process(new TempConsIncreWarning(10))
                .print();
        env.execute();
    }

    public static class TempConsIncreWarning extends KeyedProcessFunction<Tuple, SenSorReading, String> {
        //检测时间间隔区域
        private Integer interval;
        //定义状态，存储上一次输入进来的时间数据
        private ValueState<Double> lastTempState;
        //定义状态，定时器的时间戳
        private ValueState<Long> timerState;

        @Override
        public void open(Configuration parameters) throws Exception {
            lastTempState = getRuntimeContext().getState(new ValueStateDescriptor<Double>("lastTempState", Double.class, Double.MIN_VALUE));
            timerState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timerState", Long.class));
        }

        public TempConsIncreWarning(Integer interval) {
            this.interval = interval;
        }

        @Override
        public void processElement(SenSorReading senSorReading, Context context, Collector<String> collector) throws Exception {
            //取出状态
            Double lastTemp = lastTempState.value();
            Long timerTs = timerState.value();

            //如果温度上升并且没有注册定时器的时候就注册十秒的定时器
            if (senSorReading.getTemperature() > lastTemp && timerTs == null) {
                Long ts = context.timerService().currentProcessingTime() + interval * 1000;
                context.timerService().registerProcessingTimeTimer(ts);
                timerState.update(ts);
            }
            //如果温度下降删除定时器
            else if (senSorReading.getTemperature() < lastTemp && timerTs != null) {
                context.timerService().deleteProcessingTimeTimer(timerTs);
                timerState.clear();
            }

            //更新温度状态
            lastTempState.update(senSorReading.getTemperature());
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            out.collect("传感器" + ctx.getCurrentKey().getField(0) + "温度连续" + interval + "s上升!");
            timerState.clear();
        }

        @Override
        public void close() throws Exception {
            lastTempState.clear();
            timerState.clear();
        }
    }
}
